import logging
import os
import argparse
from Disassembly import Disassembly
from OpenCSD import OpenCSD
from TraceDumpDecoder import TraceDumpDecoder


def run(opencsd_path, trace_ID, snap_bin_path, compiler_path, ELF_path, output_file):

    # setting up logfile
    logfile = "logfile.log"
    logging.basicConfig(
        filename=logfile,
        level=logging.DEBUG,
        format="%(asctime)s - %(levelname)s : %(message)s",
        filemode="w",
    )
    logging.info("Logfile has started")

    opencsd = OpenCSD(opencsd_path, snap_bin_path, int(trace_ID, 16))

    disassem = Disassembly(compiler_path, ELF_path)

    dump = TraceDumpDecoder(disassem.getDisassemble(), opencsd.getTrace(), output_file)
    dump.dumpDecode()

    print(
        f"The trace decoder was running successfully. Please check file {os.path.abspath(output_file)} for output."
    )

    return True


def main():

    def is_dir(dirname):
        if not os.path.isdir(dirname):
            raise argparse.ArgumentTypeError(f"{dirname} is not a valid directory")
        return dirname

    def is_file(filename):
        if not os.path.isfile(filename):
            raise argparse.ArgumentTypeError(f"{filename} is not a valid file")
        return filename

    # initialise parser
    parser = argparse.ArgumentParser(
        description="Decode trace captured using combination of ETE and TRBE via command line"
    )
    parser.add_argument(
        "-s",
        "--ocsd",
        type=is_dir,
        metavar="",
        required=True,
        help="OpenCSD install location",
    )
    parser.add_argument(
        "-id", "--traceID", metavar="", required=True, help="ATB Trace ID"
    )
    parser.add_argument(
        "-b",
        "--snapbin",
        type=is_dir,
        metavar="",
        required=True,
        help="Snapshots and binaries location",
    )
    parser.add_argument(
        "-c",
        "--compiler",
        type=is_dir,
        metavar="",
        required=True,
        help="Arm Compiler location",
    )
    parser.add_argument(
        "-e", "--elf", type=is_file, metavar="", required=True, help="ELF file location"
    )
    parser.add_argument(
        "-o",
        "--output",
        metavar="",
        help="Specify location of output trace text file. Will write to current directory by default",
        default="trace_full.txt",
    )
    args = parser.parse_args()

    # variables to be passed into following scripts
    run(args.ocsd, args.traceID, args.snapbin, args.compiler, args.elf, args.output)


if __name__ == "__main__":
    main()
